import os

class stusystem():
    filepaht = 'C:\\Users\\hwzha\\Desktop\\file\\stusystem.txt'
    stulit = []

    def __init__(self):
        self.menum()

    def menum(self) :
        print('===============================学生信息管理系统==================================')
        print('-----------------------------------功能菜单-------------------------------------')
        print('\t\t\t\t\t\t\t1.录入学生信息')
        print('\t\t\t\t\t\t\t2.查找学生信息')
        print('\t\t\t\t\t\t\t3.删除学生信息')
        print('\t\t\t\t\t\t\t4.修改学生信息')
        print('\t\t\t\t\t\t\t5.排序')
        print('\t\t\t\t\t\t\t6.统计学生总人数')
        print('\t\t\t\t\t\t\t7.显示所有学生信息')
        print('\t\t\t\t\t\t\t0.退出系统')
        print('--------------------------------------------------------------------------------')
        self.start()

    def start(self):
        while True :
            number = int(input('请输入需要执行的代码：'))
            if number == 1 :
                self.writelist()
            elif number == 2 :
                self.selectlist()
            elif number == 3 :
                self.detlist()
            elif number ==4 :
                self.updatelist()
            elif number == 5 :
                self.orderlist()
            elif number == 6:
                self.countlist()
            elif number == 7 :
                self.show_all_list()
            elif number == 0 :
                answer = input('确定退出系统吗？y/n')
                if(answer.lower() == 'y') :
                    print('欢迎使用')
                    break
                else:
                    continue

    def writelist(self) :
        list = []
        while True :
            id   = input('输入学号如1001：')
            name = input('姓名?');
            if id == '' or name == '' :
                print('学号，姓名不能为空')
                continue
            try :
                gender = input('性别(0：女 1：男)?');
                age = input('年龄?');
                if gender:
                    gender = '男'
                else:
                    gender = '女'
            except :
                print('未知错误')

            row = {'id': id, 'name': name, 'gender': gender, 'age': age}
            list.append(row)
            go = input('继续添加学生信息吗？y/n\n')
            if go.lower() == 'y' :
                continue
            else :
                break
        self.fileWrite(list)
        self.show_all_list()
        print('录入完成')

    def selectlist(self) :
        student = []
        while True :
            par = int(input('请输入学号(如1001):'))
            list = self.getlist()
            d ={}
            for row in list :
                if int(row['id']) == par :
                    student.append(row)
            self.showlist(student)
            student.clear()
            if input('是否继续查找？').lower()=='y' :
                continue
            else:
                break

    def detlist(self) :
        while True :
            id = input('请填写需要删除的学生id(如1001)')
            list = self.getlist()
            new = []
            for row in list :
                if row['id'] == id :
                    continue
                else :
                    new.append(row)
            self.fileWrite(new, 'w')
            self.show_all_list()
            if not new :
                print('没有数据了')
                break
            if input('是否继续删除？y/n').lower() == 'y' :
                continue
            else :
                break

    def updatelist(self) :
        newlist = []
        while True :
            id = input('请输入需要修改的学号（如1001）：')
            if id == '':
                print('学号不能为空')
                break
            try:
                name = input('姓名?');
                gender = input('性别(0：女 1：男)?');
                age = input('年龄?');
                if gender != '' and gender !=0 :
                    if gender==1:
                        gender = '男'
                    else:
                        gender = '女'
                list = self.getlist()
                for row in list :
                    if int(row['id']) == int(id) :
                        row['name'] = name if name else row['name']
                        row['gender'] = gender if gender else row['gender']
                        row['age'] = age if age else row['age']
                    newlist.append(row)
                    self.fileWrite(newlist,'w')
                self.show_all_list()
                if input('继续修改吗？y/n').lower() == 'y' :
                    continue
                else:
                    break
            except:
                print('未知错误')

    def orderlist(self) :
        self.show_all_list()
        list = self.getlist()
        asc_or_desc = input('请选择0.升序，1.降序')
        if asc_or_desc == '0' :
            asc_or_desc_bool = False
        elif asc_or_desc == '1' :
            asc_or_desc_bool = True
        else :
            print('您的输入有误请重新输入')
            self.orderlist()
        mode = input('请选择排序方式 1.按学号 2.按性别 3.按年龄')
        if mode == '1' :
            list.sort(key=lambda x:x['id'],reverse=asc_or_desc_bool)
        elif mode == '2' :
            list.sort(key=lambda x:x['gender'],reverse=asc_or_desc_bool)
        elif mode == '3' :
            list.sort(key=lambda x:x['age'], reverse=asc_or_desc_bool)
        else :
            print('输入有误')
            self.orderlist()
        self.showlist(list)

    def countlist(self) :
        list = self.getlist()
        print('一共余有学生{}名'.format(len(list)))

    def show_all_list(self):
        list = self.getlist()
        self.showlist(list)

    def showlist(self,list) :
        if len(list) == 0 :
            print('没有查询到学生信息，无数据显示')
            return
        #定义表头
        row_style = '{:^6}\t{:^12}\t{:^6}\t{:^6}'
        print(row_style.format('Id','姓名','性别','年龄'))
        for row in list :
            print(row_style.format(row['id'],row['name'],row['gender'],row['age']))

    def fileWrite(self,list,method='a+'):
        with open(self.filepaht,method) as file :
            for row in list :
                file.writelines(str(row) + '\n')

    def getlist(self) :
        list = []
        if os.path.exists(self.filepaht) :
            with open(self.filepaht,'r') as file :
                content = file.readlines();
                if content :
                    for row in content :
                        d = dict(eval(row))
                        list.append(d)
        return list




stu =  stusystem()



